package com.younion.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Comparator;
import java.util.TreeMap;

import org.apache.log4j.Logger;

/**
 * @author wells
 */
public class ParametersUtils {
	private Logger logger = Logger.getLogger(this.getClass());
	private TreeMap<String, String> params = new TreeMap<String, String>(new Comparator<Object>() {
		public int compare(Object o1, Object o2) {
			if (o1 == null || o2 == null)
				return 0;
			else
				return String.valueOf(o1).compareTo(String.valueOf(o2));
		}
	});

	public ParametersUtils() {

	}

	/**
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public void addParam(String key, String value) {
		if (null == key || "".equals(key) || null == value) {
		} else {
			params.put(key.trim(), value.trim());
		}
	}

	/**
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public void addStringParam(String key, String value) {
		addParam(key, value);
	}

	/**
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public void addStringParam(String key, Number value) {
		addParam(key, value.toString());
	}

	/**
	 * 
	 * @param params
	 * @param charset
	 * @return
	 */
	public String makeSign(TreeMap<String, String> params, String secretKey, String charset) {
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
		try {
			for (String key : params.keySet()) {
				logger.debug(" sign key : " + key + " value: " + params.get(key) + " bytes2Hex:"
						+ bytes2Hex(params.get(key).getBytes(charset)));
				// byteStream.write(params.get(key).getBytes(charset));
				byteStream.write(params.get(key).getBytes(charset));
			}
			byteStream.write(secretKey.getBytes(charset));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] array = byteStream.toByteArray();
		String sign = MD5.makeMd5Sum(array);
		addStringParam("api_sign", sign);
		return sign;
	}

	/**
	 * 
	 * 
	 * @param apiSecret
	 * @return
	 */
	public String getEncryptionSign(String apiSecret) {
		String encryptionSign = makeSign(params, apiSecret, "utf-8");
		return encryptionSign;
	}

	private static String bytes2Hex(byte[] byteArray) {
		StringBuffer strBuf = new StringBuffer();
		for (int i = 0; i < byteArray.length; i++) {
			if (byteArray[i] >= 0 && byteArray[i] < 16) {
				strBuf.append("0");
			}
			strBuf.append(Integer.toHexString(byteArray[i] & 0xFF));
		}
		return strBuf.toString();
	}

}
